﻿// SilverlightDesktop.Net - http://www.SilverlightDesktop.net
// Copyright (c) 2008
// by SilverlightDesktop.Net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
//
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Collections.Generic;
using System.Threading;
using SilverlightDesktopCore.DAL;

public partial class Administration_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Must be a logged in Administrator             
        if (User.Identity.IsAuthenticated)
        {
            FormsIdentity id = (FormsIdentity)User.Identity;
            FormsAuthenticationTicket ticket = id.Ticket;
            if (!(ticket.UserData.ToString() == "Administrators"))
            {
                Response.Redirect("../Default.aspx");
                Response.End();
            }

        }
        else
        {
            Response.Redirect("../Default.aspx");
            Response.End();
        }

        if (!Page.IsPostBack)
        {
            mvAdministration.SetActiveView(vwGeneralSettings);
            LoadGeneralSettings();
            LoadAutoLoadModuleList();
            LoadDesktopInstances();
        }
    }

    #region LoadGeneralSettings
    private void LoadGeneralSettings()
    {
        GeneralSettings GeneralSettings = new GeneralSettings();
        lblVersion.Text = GeneralSettings.Version;
        ddlAnonymousLogin.SelectedValue = Convert.ToString(GeneralSettings.AnonymousLogin);
        txtMaxPasswordAttempts.Text = Convert.ToString(GeneralSettings.MaxLoginAttempts);
        txtSMTPEmailServer.Text = GeneralSettings.SMTPServer;
        rbAuthendication.SelectedValue = GeneralSettings.SMTPAuthendication;
        chkSecureAccess.Checked = GeneralSettings.SMTPSecure;
        txtSMTPUsername.Text = GeneralSettings.SMTPUserName;
        txtSMTPPassword.Text = GeneralSettings.SMTPPassword;
        txtSMTPFrom.Text = GeneralSettings.SMTPFromEmail;
    }
    #endregion

    #region Navigation
    protected void AdministrationMenu_MenuItemClick(object sender, MenuEventArgs e)
    {
        switch (e.Item.Value)
        {
            case "General Settings":
                mvAdministration.SetActiveView(vwGeneralSettings);
                break;
            case "User Management":
                mvAdministration.SetActiveView(vwUserManagement);
                break;
            case "Module Settings":
                mvAdministration.SetActiveView(vwModuleSettings);
                break;
            case "Desktops":
                mvAdministration.SetActiveView(vwDesktops);
                break;
            case "Application Log":
                mvAdministration.SetActiveView(vwApplicationLog);
                break;
        }
    }
    #endregion

    #region Update Settings
    protected void btnUpdateSettings_Click(object sender, EventArgs e)
    {
        try
        {
            GeneralSettings.UpdateAnonymousLogin(Convert.ToBoolean(ddlAnonymousLogin.SelectedValue));
            GeneralSettings.UpdateMaxLoginAttempts(Convert.ToInt32(txtMaxPasswordAttempts.Text.Trim()));
            GeneralSettings.UpdateSMTPServer(txtSMTPEmailServer.Text.Trim());
            GeneralSettings.UpdateSMTPAuthendication(rbAuthendication.SelectedValue);
            GeneralSettings.UpdateSMTPSecure(chkSecureAccess.Checked);
            GeneralSettings.UpdateSMTPUserName(txtSMTPUsername.Text.Trim());
            GeneralSettings.UpdateSMTPPassword(txtSMTPPassword.Text.Trim());
            GeneralSettings.UpdateSMTPFromEmail(txtSMTPFrom.Text.Trim());
        }
        catch (Exception ex)
        {
            lblUpdated.Text = ex.Message;
            return;
        }

        lblUpdated.Text = "Updated!";
    }
    #endregion

    #region Send Test Email
    protected void lnkTestEmail_Click(object sender, EventArgs e)
    {
        // Send Test Email
        // For normal emails use this constructor:
        // SendMail(string MailTo, string Cc, string Bcc, string ReplyTo, string Subject, string Body, string strAttachment)

        string[] arrAttachments = new string[0];
        string strEmailResponse = Email.SendMail(txtSMTPFrom.Text.Trim(), txtSMTPFrom.Text.Trim(), "", "", txtSMTPFrom.Text.Trim(), MailPriority.Normal, "SilverlightDesktop Email", Encoding.UTF8, "A test email sent from SilverlightDesktop",
        arrAttachments, txtSMTPEmailServer.Text.Trim(), rbAuthendication.SelectedValue, txtSMTPUsername.Text.Trim(), txtSMTPPassword.Text.Trim(), chkSecureAccess.Checked);

        lblUpdated.Text = (strEmailResponse.Trim() == "") ? "Email Sent." : strEmailResponse;
    }
    #endregion

    #region lnkRefresh
    protected void lnkRefresh_Click(object sender, EventArgs e)
    {
        gvApplicationLog.DataBind();
    }
    #endregion

    #region lvUsers_ItemInserted
    protected void lvUsers_ItemInserted(object sender, ListViewInsertedEventArgs e)
    {
        if (e.Exception != null)
        {
            lblError.Text = e.Exception.Message;
            e.KeepInInsertMode = true;
            e.ExceptionHandled = true;
        }
    }
    #endregion

    #region lvUsers_ItemUpdated
    protected void lvUsers_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
    {
        if (e.Exception != null)
        {
            lblError.Text = e.Exception.Message;
            e.KeepInEditMode = true;
            e.ExceptionHandled = true;
        }
    }
    #endregion

    #region ListView1_ItemInserted
    protected void ListView1_ItemInserted(object sender, ListViewInsertedEventArgs e)
    {
        if (e.Exception != null)
        {
            lblModuleError.Text = e.Exception.Message;
            e.KeepInInsertMode = true;
            e.ExceptionHandled = true;
        }
    }
    #endregion


    // Module Install

    string strAppBase = "";
    string strTempDirectory = "";
    ListItemCollection UploadMessage = new ListItemCollection();

    #region Install Module
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (File1.PostedFile.FileName == "")
        {
            return;
        }

        try
        {
            SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

            strAppBase = Server.MapPath(@"..\");
            strTempDirectory = Server.MapPath(@"..\") + @"Temp\";

            // Create a Temp Directory
            if (Directory.Exists(strTempDirectory))
            {
                Directory.Delete(strTempDirectory, true);
            }

            try
            {
                Directory.CreateDirectory(strTempDirectory);
            }
            catch (Exception)
            {
                // try again this time give the system time to delete the files first
                Thread.Sleep(5000);
                Directory.CreateDirectory(strTempDirectory);
            }

            string strZipFilename = File1.PostedFile.FileName;
            strZipFilename = System.IO.Path.GetFileName(strZipFilename);
            File1.PostedFile.SaveAs(strTempDirectory + strZipFilename);

            UploadMessage.Add(String.Format("File saved to {0}", strTempDirectory + strZipFilename));
            UnzipFile(strTempDirectory + strZipFilename);

            // Load the config file
            XElement doc = XElement.Load(strTempDirectory + @"\Module.config");

            string strconfigversion = doc.Element("configversion").Value;
            string strconfigtype = doc.Element("configtype").Value;
            string strmodulename = doc.Element("modulename").Value;
            string strdescription = doc.Element("description").Value;
            string strassembly = doc.Element("assembly").Value;
            string strversion = doc.Element("version").Value;
            string strclass = doc.Element("class").Value;
            string stricon = doc.Element("icon").Value;
            string strrole = doc.Element("role").Value;
            string strwindowsize = doc.Element("windowsize").Value;

            if (strconfigtype.ToLower() != "module")
            {
                UploadMessage.Add(String.Format("Attempted to install type {0}. Only ConfigType Module can be installed. Aborting installation.", strconfigtype));
                CompleteModuleInstall(true);
                return;
                // Exit
            }

            // Build a list of files to remove
            List<string> colFilesToRemove = new List<string>();
            foreach (XElement Element in doc.Element("removefiles").Elements())
            {
                colFilesToRemove.Add(Element.Value);
            }

            colFilesToRemove.Sort();

            // Get the current module version if any
            int intCurrentModuleVersion = 0;
            var result = from Module in SilverlightDesktopDAL.SilverlightDesktopModules
                         where Module.ModuleName.ToLower() == strmodulename.ToLower()
                         select Module.ModuleVersion;

            intCurrentModuleVersion = (result.FirstOrDefault().ToString() == "") ? intCurrentModuleVersion : result.FirstOrDefault();

            int intModuleVersion = Convert.ToInt32(strversion.Replace(".", ""));

            if (intModuleVersion <= intCurrentModuleVersion)
            {
                UploadMessage.Add(String.Format("Current module version is {0}. Installing module version is {1}. Aborting installation.", intCurrentModuleVersion.ToString(), intModuleVersion.ToString()));
                CompleteModuleInstall(true);
                return;
                // Exit
            }
            else
            {
                UploadMessage.Add(String.Format("Current module version is {0}. Installing module version {1}.", intCurrentModuleVersion.ToString(), intModuleVersion.ToString()));
            }

            // Get a list of all .sql scripts
            List<string> colSQLScripts = Directory.GetFiles(strTempDirectory, "*.sql").ToList();
            colSQLScripts.Sort();

            foreach (string strFile in colSQLScripts)
            {
                string strFileName = Path.GetFileNameWithoutExtension(strFile);
                if (strFileName.ToLower() != "uninstall")
                {
                    int intVersion = Convert.ToInt32(strFileName.Replace(".", ""));
                    if (intVersion <= intModuleVersion)
                    {
                        try
                        {
                            string strSqlScript = GetSQLScript(strFile);
                            SilverlightDesktopDAL.ExecuteCommand(strSqlScript);
                            File.Delete(strFile);
                            UploadMessage.Add(String.Format("SQL Script processed: {0}", strFileName));
                        }
                        catch (Exception ex)
                        {
                            UploadMessage.Add(String.Format("SQL Script error in script: {0} - {1}", strFileName, ex.ToString()));
                            CompleteModuleInstall(true);
                            return;
                        }
                    }
                }
            }

            // Update the Modules Table 

            // Delete record if it exists
            var ModuleEntry = (from Module in SilverlightDesktopDAL.SilverlightDesktopModules
                               where Module.ModuleName.ToLower() == strmodulename.ToLower()
                               select Module).FirstOrDefault();

            // // If the Module entry does not already exist, create it
            if (ModuleEntry == null)
            {
                ModuleEntry = new SilverlightDesktopCore.DAL.SilverlightDesktopModule();
            }

            ModuleEntry.AssemblyName = strassembly;
            ModuleEntry.ModuleDescription = strdescription;
            ModuleEntry.ModuleName = strmodulename;
            ModuleEntry.ClassName = strclass;
            ModuleEntry.IconName = stricon;
            ModuleEntry.Role = strrole;
            ModuleEntry.WindowSize = Convert.ToInt32(strwindowsize);
            ModuleEntry.ModuleVersion = Convert.ToInt32(strversion.Replace(".", ""));

            //Read and insert the uninstall script
            if (File.Exists(strTempDirectory + "uninstall.sql"))
            {
                string strUninstall = GetSQLScript(strTempDirectory + "uninstall.sql");
                ModuleEntry.uninstall = strUninstall;
            }

            // If the Module entry does not already exist insert it
            if (ModuleEntry.ModuleID == 0)
            {
                SilverlightDesktopDAL.SilverlightDesktopModules.InsertOnSubmit(ModuleEntry);
                UploadMessage.Add(String.Format("Created Module entry {0}", strmodulename));
            }

            SilverlightDesktopDAL.SubmitChanges();

            //Delete files
            foreach (string strDeleteFile in colFilesToRemove)
            {
                File.Delete(strTempDirectory.Replace(@"\Temp", "") + strDeleteFile);
                UploadMessage.Add(String.Format("Removed File: {0}", strDeleteFile));
            }

            //Delete the .zip, .config and uninstall files
            File.Delete(strTempDirectory + strZipFilename);
            File.Delete(strTempDirectory + "uninstall.sql");
            File.Delete(strTempDirectory + "Module.config");

            //Delete any file details in the database
            var colModuleFiles = from ModuleFiles in SilverlightDesktopDAL.SilverlightDesktopModuleFiles
                                 where ModuleFiles.ModuleName.ToLower() == strmodulename.ToLower()
                                 select ModuleFiles;

            SilverlightDesktopDAL.SilverlightDesktopModuleFiles.DeleteAllOnSubmit(colModuleFiles);
            SilverlightDesktopDAL.SubmitChanges();

            //Add The Module File information to the database

            List<string> colFiles = Utility.GetAllFileNames(strTempDirectory).ToList();
            foreach (string strFile in colFiles)
            {
                SilverlightDesktopModuleFile objModuleFile = new SilverlightDesktopModuleFile();
                objModuleFile.ModuleName = strmodulename.ToLower();
                objModuleFile.FileNameAndPath = Path.GetFullPath(strFile).ToString().Replace(strTempDirectory, "");
                SilverlightDesktopDAL.SilverlightDesktopModuleFiles.InsertOnSubmit(objModuleFile);
                SilverlightDesktopDAL.SubmitChanges();

                try
                {
                    // Move the file to it's destination
                    File.Move(strFile, strFile.Replace(@"\Temp", ""));
                }
                catch
                {
                    UploadMessage.Add(String.Format("File already exists: {0}", strFile.Replace(@"\Temp", "")));
                    // Delete the file instead
                    File.Delete(strFile);
                }
            }

            // Cleanup
            Directory.Delete(strTempDirectory, true);
            UploadMessage.Add(String.Format("Temp directory removed"));
            CompleteModuleInstall(false);
        }
        catch (Exception ex)
        {
            UploadMessage.Add(ex.Message);
            CompleteModuleInstall(true);
        }
    }

    #endregion

    #region UnzipFile
    private void UnzipFile(string strZipFile)
    {
        using (ZipInputStream s = new ZipInputStream(File.OpenRead(strZipFile)))
        {
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(strTempDirectory + theEntry.Name);
                string fileName = Path.GetFileName(strTempDirectory + theEntry.Name);

                // create directory
                if (directoryName.Length > 0)
                {
                    if (!Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                        UploadMessage.Add(String.Format("Directory Created {0}", directoryName));
                    }
                }

                if (fileName != String.Empty)
                {
                    using (FileStream streamWriter = File.Create(strTempDirectory + theEntry.Name))
                    {
                        UploadMessage.Add(String.Format("File Unzipped: {0}", theEntry.Name));
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    #endregion

    #region GetSQLScript
    private String GetSQLScript(string PathandScript)
    {
        string strSQLScript;
        StreamReader reader = new StreamReader(PathandScript);
        strSQLScript = reader.ReadToEnd();
        reader.Close();
        reader = null;
        return strSQLScript;
    }
    #endregion

    #region DeleteModule
    protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        strAppBase = Server.MapPath(@"..\");
        //Run the uninstall script if there is one
        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

        // Get the selected module
        var objModule = (from Module in SilverlightDesktopDAL.SilverlightDesktopModules
                         where Module.ModuleID == Convert.ToInt32(e.Keys[0])
                         select Module).FirstOrDefault();

        if (objModule.uninstall.Trim() != "")
        {
            SilverlightDesktopDAL.ExecuteCommand(objModule.uninstall.Trim());
        }

        // Get the files for the module and delete them
        var objModules = from Modules in SilverlightDesktopDAL.SilverlightDesktopModuleFiles
                         where Modules.ModuleName.ToLower() == objModule.ModuleName.ToLower()
                         select Modules;

        foreach (var tmpModule in objModules)
        {
            string strFileToDelte = (strAppBase + "\\" + tmpModule.FileNameAndPath).Replace("\\\\", "\\");
            File.Delete(strFileToDelte);

            // Log the event
            ApplicationLog.AddToLog(String.Format("Module: {0} - File deleted {1}.", objModules.FirstOrDefault().ModuleName, strFileToDelte));
        }

        // Delete entries in moduleFiles table
        SilverlightDesktopDAL.SilverlightDesktopModuleFiles.DeleteAllOnSubmit(objModules);
        SilverlightDesktopDAL.SubmitChanges();
        // Refresh the Log
        gvApplicationLog.DataBind();
    }
    #endregion

    #region CompleteModuleInstall
    private void CompleteModuleInstall(bool HasErrors)
    {
        // Refresh the module list
        ListView1.DataBind();
        LoadAutoLoadModuleList();

        // Log all events
        foreach (ListItem strUploadMessage in UploadMessage)
        {
            ApplicationLog.AddToLog(strUploadMessage.Value);
        }

        if (HasErrors)
        {
            // Cleanup
            Directory.Delete(strTempDirectory, true);
            ApplicationLog.AddToLog("Temp directory removed");
            gvApplicationLog.DataBind();
            mvAdministration.SetActiveView(vwApplicationLog);
        }
    }
    #endregion

    // Desktop Instance

    #region LoadDesktopInstances
    private void LoadDesktopInstances()
    {
        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();
        List<SilverlightDesktopCore.DAL.SilverlightDesktopInstance> result = (from Instances in SilverlightDesktopDAL.SilverlightDesktopInstances
                                                                              select Instances).ToList();

        SilverlightDesktopCore.DAL.SilverlightDesktopModule objSilverlightDesktopModule = new SilverlightDesktopCore.DAL.SilverlightDesktopModule();

        ddlDesktopInstances.DataSource = result;
        ddlDesktopInstances.DataBind();

        pnlSelectDesktop.Visible = (result.Count > 0) ? true : false;
        ddlDesktopInstances.Visible = (result.Count > 0) ? true : false;
        lblSelectDesktop.Visible = (result.Count > 0) ? true : false;
        lnkNewDesktop.Visible = (result.Count > 0) ? true : false;
        btnDeleteInstance.Visible = (result.Count > 0) ? true : false;
        btnSaveDesktopInstance.Text = (result.Count > 0) ? "Save" : "Add Desktop Instance";
        int intDesktopInstance = (result.Count > 0) ? Convert.ToInt32(ddlDesktopInstances.SelectedValue) : 0;
        LoadDesktopInstance(intDesktopInstance);
    }
    #endregion

    #region LoadAutoLoadModuleList
    private void LoadAutoLoadModuleList()
    {
        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();
        List<SilverlightDesktopCore.DAL.SilverlightDesktopModule> result = (from Module in SilverlightDesktopDAL.SilverlightDesktopModules
                                                                            select Module).ToList();

        SilverlightDesktopCore.DAL.SilverlightDesktopModule objSilverlightDesktopModule = new SilverlightDesktopCore.DAL.SilverlightDesktopModule();
        objSilverlightDesktopModule.ModuleID = 0;
        objSilverlightDesktopModule.ModuleName = "(none)";

        result.Add(objSilverlightDesktopModule);

        result = (from Module in result
                  orderby Module.ModuleID
                  select Module).ToList();

        ddlAutoLoadModule.SelectedValue = "0";
        ddlAutoLoadModule.DataSource = result;
        ddlAutoLoadModule.DataBind();
    }
    #endregion

    #region lnkNewDesktop_Click
    protected void lnkNewDesktop_Click(object sender, EventArgs e)
    {
        NewDesktopInstance();
    }
    #endregion

    #region NewDesktopInstance
    private void NewDesktopInstance()
    {
        DesktopNameTextBox.Text = "";
        DesktopSizeHorizontalTextBox.Text = "";
        DesktopSizeVerticalTextBox.Text = "";
        TransparentCheckBox.Checked = false;
        ddlAutoLoadModule.SelectedValue = "0";
        btnSaveDesktopInstance.Text = "Add Desktop Instance";
        btnDeleteInstance.Visible = false;
        DesktopNameTextBox.Enabled = true;
    }
    #endregion

    #region btnSaveDesktopInstance_Click
    protected void btnSaveDesktopInstance_Click(object sender, EventArgs e)
    {
        if (btnSaveDesktopInstance.Text == "Add Desktop Instance")
        {
            // An Insert
            SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

            SilverlightDesktopInstance SilverlightDesktopInstance = new SilverlightDesktopInstance();
            SilverlightDesktopInstance.DesktopName = DesktopNameTextBox.Text;
            SilverlightDesktopInstance.DesktopSizeHorizontal = ConverToNumber(DesktopSizeHorizontalTextBox.Text);
            SilverlightDesktopInstance.DesktopSizeVertical = ConverToNumber(DesktopSizeVerticalTextBox.Text);
            SilverlightDesktopInstance.Transparent = TransparentCheckBox.Checked;
            SilverlightDesktopInstance.ShowToolbar = (ddlAutoLoadModule.SelectedValue == "(none)") ? true : false;
            SilverlightDesktopInstance.AutoLoadModule = Convert.ToInt32(ddlAutoLoadModule.SelectedValue);

            SilverlightDesktopDAL.SilverlightDesktopInstances.InsertOnSubmit(SilverlightDesktopInstance);
            SilverlightDesktopDAL.SubmitChanges();

            LoadDesktopInstances();
        }
        else
        {
            // An Update
            int intDesktopInstance = Convert.ToInt32(ddlDesktopInstances.SelectedValue);
            SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();

            SilverlightDesktopInstance SilverlightDesktopInstance = (from Instances in SilverlightDesktopDAL.SilverlightDesktopInstances
                                                                     where Instances.ID == intDesktopInstance
                                                                     select Instances).FirstOrDefault();

            SilverlightDesktopInstance.DesktopName = DesktopNameTextBox.Text;
            SilverlightDesktopInstance.DesktopSizeHorizontal = ConverToNumber(DesktopSizeHorizontalTextBox.Text);
            SilverlightDesktopInstance.DesktopSizeVertical = ConverToNumber(DesktopSizeVerticalTextBox.Text);
            SilverlightDesktopInstance.Transparent = TransparentCheckBox.Checked;
            SilverlightDesktopInstance.ShowToolbar = (ddlAutoLoadModule.SelectedValue == "(none)") ? true : false;
            SilverlightDesktopInstance.AutoLoadModule = Convert.ToInt32(ddlAutoLoadModule.SelectedValue);

            SilverlightDesktopDAL.SubmitChanges();
            lblInstanceUpdated.Visible = true;
        }
    }
    #endregion

    #region ConverToNumber
    private int ConverToNumber(string value)
    {
        int number;
        bool result = Int32.TryParse(value, out number);
        if (!result)
        {
            number = 100;
        }
        return number;
    }
    #endregion

    #region ddlDesktopInstances_SelectedIndexChanged
    protected void ddlDesktopInstances_SelectedIndexChanged(object sender, EventArgs e)
    {
        int intDesktopInstance = Convert.ToInt32(ddlDesktopInstances.SelectedValue);
        LoadDesktopInstance(intDesktopInstance);
    }
    #endregion

    #region LoadDesktopInstance
    private void LoadDesktopInstance(int intDesktopInstance)
    {
        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();
        var result = (from Instances in SilverlightDesktopDAL.SilverlightDesktopInstances
                      where Instances.ID == intDesktopInstance
                      select Instances).FirstOrDefault();

        if (result != null)
        {
            DesktopNameTextBox.Enabled = false;
            DesktopNameTextBox.Text = result.DesktopName;
            DesktopSizeHorizontalTextBox.Text = result.DesktopSizeHorizontal.ToString();
            DesktopSizeVerticalTextBox.Text = result.DesktopSizeVertical.ToString();
            TransparentCheckBox.Checked = result.Transparent;
            try
            {
                ddlAutoLoadModule.SelectedValue = result.AutoLoadModule.ToString();
            }
            catch
            {
                ddlAutoLoadModule.SelectedValue = "0";
            }
        }
        else
        {
            NewDesktopInstance();
        }
    }
    #endregion

    #region btnDeleteInstance_Click
    protected void btnDeleteInstance_Click(object sender, EventArgs e)
    {
        int intDesktopInstance = Convert.ToInt32(ddlDesktopInstances.SelectedValue);

        SilverlightDesktopDAL SilverlightDesktopDAL = new SilverlightDesktopDAL();
        var result = (from Instances in SilverlightDesktopDAL.SilverlightDesktopInstances
                      where Instances.ID == intDesktopInstance
                      select Instances).FirstOrDefault();

        if (result != null)
        {
            SilverlightDesktopDAL.SilverlightDesktopInstances.DeleteOnSubmit(result);
            SilverlightDesktopDAL.SubmitChanges();
        }

        LoadDesktopInstances();
    }
    #endregion

    #region btnCancelDesktopInstance_Click
    protected void btnCancelDesktopInstance_Click(object sender, EventArgs e)
    {
        LoadDesktopInstances();
    } 
    #endregion
}
